<template>
    <el-container class="container" v-loading="loading">
        <h1>Search</h1>
        <div class="searchbar">
            <div class="search-left">
                <KeepAlive>
                    <EsSearchBar v-model="inputVal" @select="onSelectChange" />
                </KeepAlive>
            </div>

            <!-- 按钮区域：放在搜索栏右侧 -->
            <div class="search-actions">
                <el-space>
                    <el-button type="primary" :loading="exportingFiltered" @click="downloadFiltered">
                        导出表格数据
                    </el-button>
                </el-space>
            </div>
        </div>
        <LifeLines :selectedSampleIDs="selectedSampleIDs" />
        <div class="table">
            <el-table :data="tableData" @sort-change="onSortChange" style="width: 100%">
                <el-table-column prop="SampleID" label="SampleID" min-width="120" />
                <el-table-column prop="OSTime" label="OS.time" sortable="custom" min-width="80" />
                <el-table-column prop="OSStatus" label="OS.status" min-width="80" />
                <el-table-column prop="PFSTime" label="PFS.time" min-width="80" />
                <el-table-column prop="PFSStatus" label="PFS.status" min-width="80" />
                <el-table-column prop="age" label="age" min-width="80" />
                <el-table-column prop="gender" label="gender" min-width="80" />
                <el-table-column prop="treatment" label="treatment" min-width="120" />
                <el-table-column prop="subType" label="subType" min-width="120" />
                <!-- <el-table-column label="Options" width="120" align="center">
                    <template #default="{ row }">
                        <el-text type="primary" style="cursor: pointer" @click="onViewDetails(row.SampleID)">
                            checkDetail
                        </el-text>
                    </template>
                </el-table-column> -->
            </el-table>
        </div>
        <div class="pagination">
            <el-pagination
                background
                :page-size="currentPageSize"
                :total="total"
                :current-page="currentPage"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
    </el-container>
</template>

<script lang="ts" setup name="SearchPage">
    import { onMounted, ref } from 'vue';
    import EsSearchBar from '@/components/EsSearchBar.vue';
    import LifeLines from '@/components/LifeLines.vue';
    import { useRouter } from 'vue-router';
    import { get, post } from '@/axios/api';
    import { loadUser, useAuth } from '@/common/useAuth';
    import { ElMessage } from 'element-plus';

    const { user } = useAuth();

    let inputVal: any = ref('');
    let tableData: any = ref([]);
    const currentPage = ref(1);
    const currentPageSize = ref(10);
    const total = ref(0);
    const loading = ref(false);

    const selectedValues: any = ref();
    const router = useRouter();
    const selectedSampleIDs = ref([]);
    const exportingFiltered = ref(false);
    const exportingSelected = ref(false);

    let sortedProp = ref('SampleID');
    let sortedOrder = ref('desc');

    async function downloadFiltered() {
        exportingFiltered.value = true;
        try {
            const body = {
                // 如果你有当前的筛选条件、sort 信息，应该一并传给后端
                selected: selectedValues.value, // 或者把当前筛选条件写在 selected 中
                sort_by: sortedProp.value,
                sort_order: sortedOrder.value
                // 其它可能的筛选字段: fromDate, toDate, sample_type...
            };
            await postDownload(body, 'filtered_clinical_data.csv');
        } finally {
            exportingFiltered.value = false;
        }
    }

    async function postDownload(body:any, filename = 'clinical_data.csv') {
        try {
            const res = await post('/clinical-data/export/', body, {
                responseType: 'blob' // 告诉浏览器我们要二进制
            });

            let blobData:any = res;
            // 如果仍不是 Blob（比如后端返回了 string），把它转换为 Blob
            if (!(blobData instanceof Blob)) {
                // 尝试从 headers 获取 content-type；否则默认 text/csv
                const contentType = 'text/csv;charset=utf-8';
                blobData = new Blob([blobData], { type: contentType });
            }

            const url = window.URL.createObjectURL(blobData);
            const a = document.createElement('a');
            a.href = url;

            // 尝试从后端 Content-Disposition 解析文件名（如果需要更复杂解析可扩展）
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            a.remove();
            window.URL.revokeObjectURL(url);
        } catch (err) {
            console.error('导出失败', err);
            // 可用 Element Plus 的 ElMessage 提示用户：
            // ElMessage.error('导出失败，请检查网络或服务器日志')
            throw err;
        }
    }
    function onSelectChange(event: any) {
        console.log(event);
        // selectedValues 就是已经选中过的条件，为一个obj，下边的每个键值对都是一个数组
        selectedValues.value = event.grouped;
        search(currentPage.value, currentPageSize.value, sortedProp.value, sortedOrder.value);
    }

    async function handleSizeChange(val: number) {
        currentPageSize.value = val;
        search(currentPage.value, val, sortedProp.value, sortedOrder.value);
    }

    async function handleCurrentChange(val: number) {
        currentPage.value = val;
        search(val, currentPageSize.value, sortedProp.value, sortedOrder.value);
    }

    async function search(page = 1, pageSize = 10, sort_by: any, sort_order: any) {
        loading.value = true;
        try {
            const res: any = await post('/clinical-data/get-data/', {
                selected: selectedValues.value,
                page: page,
                page_size: pageSize,
                sort_by: sort_by,
                sort_order: sort_order
            });
            if (res && res.success) {
                tableData.value = res.results;
                loading.value = false;
                currentPage.value = res.page;
                total.value = res.total;
                selectedSampleIDs.value = res.selectedSampleIDs;
            }
        } catch (err) {
            console.error(err);
        }
    }

    function onViewDetails(SampleID: string) {
        router.push({
            name: 'search-detail',
            params: {
                SampleID
            }
        });
    }

    function onSortChange(event: any) {}

    onMounted(async() => {
        await loadUser(); 
        if (!user.value) {
            ElMessage.error('请先登录');
            setTimeout(() => {
                router.push({name: "login"});
            }, 1000)
        }
        search(currentPage.value, currentPageSize.value, sortedProp.value, sortedOrder.value);
    });
</script>

<style lang="scss" scoped>
    .container {
        width: 100%;
        display: flex;
        flex-direction: column;
    }

    .searchbar {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between; /* 左搜索，右按钮 */
        gap: 12px;
        margin-bottom: 12px;

        .search-left {
            flex: 1 1 auto;
        }
        .search-actions {
            flex: 0 0 auto;
        }
    }

    .pagination {
        margin-top: 12px;
        display: flex;
        justify-content: flex-end;
        align-items: center;
    }
</style>
